<?php

namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use app\common\model\SchoolStunoModel;

/**
 * Class SchoolStuno
 */
class SchoolStuno extends BasicAdmin
{

    /**
     * 学校学号管理
     */
    protected $model = 'SchoolStunoModel';

    public function index(){
        $this->title = '学校学号管理';
        return  $this->_query($this->model)
            ->like('school_name')
            ->page();
    }

    /**
     * 添加
     */
    public function add()
    {
        $this->title = '添加';
        return $this->_form($this->model, 'form');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $this->title = '编辑';
        return $this->_form($this->model, 'form');
    }

    /**
     * 删除
     */
    public function del()
    {
        $this->_delete($this->model);
    }

    /**
     * 学号导入模板
     */
    public function import_template()
    {
        $list[0] = [
            'school_name'=>'示例请删除 深圳实验学校',
            'student_no'=>'000000001',
        ];
        $table_field = [
            ['A' ,'school_name', '学校'],
            ['B' ,'student_no','学号'],
        ];
        return $this->_export($list, $table_field, '学号导入模板');
    }

    /**
     * 课程导入
     */
    public function import()
    {
        require(dirname(__FILE__) . '/../../../vendor/spreadsheet/php-excel-reader/excel_reader2.php');
        require(dirname(__FILE__) . '/../../../vendor/spreadsheet/SpreadsheetReader.php');
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error('未上传文件');
        }else {
            $upload = array(
                'uploadurl' => 'ajax/upload',
                'cdnurl'    => '',
                'savekey'   => '/upload/excel/{filemd5}{.suffix}',
                'maxsize'   => '1024mb',
                'mimetype'  => 'xls,xlsx',
                'multiple'  => false
            );

            preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
            $type = strtolower($matches[2]);
            $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
            $size = (int)$upload['maxsize'] * pow(999999, isset($typeDict[$type]) ? $typeDict[$type] : 0);
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix ? $suffix : 'file';

            $mimetypeArr = explode(',', strtolower($upload['mimetype']));
            $typeArr = explode('/', $fileInfo['type']);

            //验证文件后缀
            if ($upload['mimetype'] !== '*' &&
                (
                    !in_array($suffix, $mimetypeArr)
                    || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
                )
            ) {
                $this->error('只能上传xls,xlsx文件');
            }
            $replaceArr = [
                '{year}'     => date("Y"),
                '{mon}'      => date("m"),
                '{day}'      => date("d"),
                '{hour}'     => date("H"),
                '{min}'      => date("i"),
                '{sec}'      => date("s"),
                '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
                '{suffix}'   => $suffix,
                '{.suffix}'  => $suffix ? '.' . $suffix : '',
                '{filemd5}'  => md5_file($fileInfo['tmp_name']),
            ];
            $savekey = $upload['savekey'];
            $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

            $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
            $fileName = substr($savekey, strripos($savekey, '/') + 1);
            $splInfo = $file->move( '/www/wwwroot/zhuoyu/public' . $uploadDir, $fileName);
            $file = '/www/wwwroot/zhuoyu/public' . $uploadDir. $fileName;
            $Reader = new \SpreadsheetReader($file);
            foreach ($Reader as $Key => $Row) {
                if ($Key != 1 && !empty($Row)) {
                    $school_name = $Row[0]; //学校名
                    $student_no = $Row[1]; //学号
                    if ($school_name&&$student_no != '') {
                        $school_name = isset($Row[0])?$Row[0]:''; //学校名
                        $student_no = isset($Row[1])?$Row[1]:''; //学号

                        SchoolStunoModel::create([
                            'school_name'=>$school_name,
                            'student_no'=>$student_no,
                        ]);
                    }
                }
            }
            $this->success('导入成功，已更新！');
        }
    }
}